<template>
  <div class="app-container">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="批量消耗撤回"
        :btn-list="btnList"
        :needReturn="false"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t("basic_information") }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-consumeDeptName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择消耗撤回部门"
                  v-model="formInfo.data.consumeDeptName"
                >
                  <template #append>
                    <el-icon @click="selectConsumeDept"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-depotName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择原出库仓库"
                  v-model="formInfo.data.depotName"
                >
                  <template #append>
                    <el-icon @click="selectExportDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <!-- <template v-slot:form-consumeDeptName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择出库部门"
                  v-model="formInfo.data.consumeDeptName"
                />
              </template> -->
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >新增行</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                  >删除行</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </template>
              <template v-slot:filter-uploadExcel>
                <el-upload
                  :headers="uploadInfo.headers"
                  :disabled="!canAddProduct"
                  :data="uploadInfo.data"
                  :show-file-list="false"
                  :on-error="uploadError"
                  :on-success="importProduct"
                  :before-upload="beforeProductUpload"
                  :action="uploadInfo.action"
                >
                  <el-button :disabled="!canAddProduct">导入模板</el-button>
                </el-upload>
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  :class="{
                    isShow:
                      selectProductInfo.popoVisible ||
                      selectBatchInfo.popoVisible,
                  }"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="false"
                  :summaryFieldList="tableInfo.summaryFieldList"
                  :tabIndex="false"
                  :check-box="true"
                  :spanMethod="spanMethod"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :cell-class-name="tableCellClassName"
                  :isDynamic="true"
                  methodKey="groupKey"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-productCode="scope">
                    <el-input
                      v-if="
                        scope.row.emptyRowType && scope.row.emptyRowType === '1'
                      "
                      :ref="'productRef' + scope.$index"
                      :class="'productKey' + scope.$index"
                      class="productKey"
                      :disabled="!canAddProduct"
                      v-model="scope.row.productKeyword"
                      placeholder="名称\编码\别名\助记符"
                      @keyup.enter="productSearchInput(scope.row, scope.$index)"
                    >
                      <template #append>
                        <div
                          class="el-input-search"
                          @click="productSearch(scope.row, scope.$index)"
                        >
                          <el-icon style="vertical-align: middle">
                            <Search />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                    <p v-else>
                      <span
                        v-if="scope.row.isExport"
                        class="consignBusiness-text"
                        >(导)</span
                      >
                      {{ scope.row.productCode }}
                    </p>
                  </template>
                  <template v-slot:col-orderNo="scope">
                    <!-- codetype 1系统唯一码  2 原厂码 3批次码 -->
                    <el-input
                      v-if="
                        scope.row.emptyRowType &&
                        (scope.row.emptyRowType === '1' ||
                          scope.row.emptyRowType === '2') &&
                        (!scope.row.codeType ||
                          scope.row.codeType === 1 ||
                          scope.row.codeType === 4)
                      "
                      :ref="'batchRef' + scope.$index"
                      :class="'batchKey' + scope.$index"
                      class="batchKey"
                      placeholder="消耗单号"
                      :disabled="!scope.row.depotStockId"
                      v-model="scope.row.batchKeyword"
                      @keyup.enter="
                        batchNumberSearchInput(scope.row, scope.$index)
                      "
                    >
                      <template #append>
                        <div
                          class="el-input-search"
                          @click="batchNumberSearch(scope.row, scope.$index)"
                        >
                          <el-icon style="vertical-align: middle">
                            <Search />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                    <template v-else>
                      <!-- <StoreBatchNumberTag :row="scope.row" str="orderNo"/> -->
                      {{ scope.row["orderNo"] || "-" }}
                    </template>
                  </template>
                  <template v-slot:col-storeBatchNumber="scope">
                    <StoreBatchNumberTag :row="scope.row" />
                    <!-- {{ scope.row["storeBatchNumber"] || "" }} -->
                  </template>
                  <template v-slot:col-price="scope">
                    <span>{{ scope.row.price }}</span>
                  </template>
                  <template v-slot:col-preInvalidQty="scope">
                    <span>{{
                      scope.row.isImportExcelDetail
                        ? scope.row.preInvalidQty
                        : "-"
                    }}</span>
                  </template>
                  <template v-slot:col-qty="scope">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        (scope.row.codeType === 1 ||
                          scope.row.codeType === 4) &&
                        !scope.row.emptyRowType
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                              />
                            </el-form-item>
                            <!-- <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div> -->
                          </div>
                          <div
                            class="page-table-input-number-item"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                                @change="
                                  changeSmall(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.smallUnitQty`
                                  )
                                "
                              />
                            </el-form-item>
                            <!-- <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div> -->
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        (scope.row.codeType === 2 ||
                          scope.row.codeType === 3) &&
                        !scope.row.emptyRowType
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <!-- 选择部门 -->
    <select-dept
      v-if="deptInfo.visible"
      v-model:showDialog="deptInfo.visible"
      :query="deptInfo.query"
      @callback="selectDeptCallback"
      :checkBox="false"
      :highlightRow="true"
      :saveEmpty="true"
    />
    <SelectProduct
      v-if="selectProductInfo.visible"
      v-model:showDialog="selectProductInfo.visible"
      :tableKey="selectProductInfo.tableKey"
      :api="individualInfo.leftApi"
      :query="selectProductInfo.query"
      :highlightRow="false"
      :checkBox="true"
      :consumeRevokeDimensionType="formInfo.data.consumeRevokeDimensionType"
      :showPrice="$permission('consume:price')"
      @callback="selectProductBackList"
    />
    <SelectBatch
      v-if="selectBatchInfo.visible"
      v-model:showDialog="selectBatchInfo.visible"
      :popoVisible="selectBatchInfo.visible"
      :tableKey="selectBatchInfo.tableKey"
      :api="getConsumeOrderDetailBatchRevokeSingleCustomizeListPage"
      :query="selectBatchInfo.query"
      :codeType="selectBatchInfo.row.codeType"
      :highlightRow="false"
      :checkBox="true"
      :showPrice="$permission('consume:price')"
      @callback="selectBatchBackList"
    ></SelectBatch>
    <SelectDepot
      v-if="selectExportDepotInfo.visible"
      v-model:showDialog="selectExportDepotInfo.visible"
      :checkBox="false"
      :query="selectExportDepotInfo.query"
      :highlightRow="true"
      :checkLock="true"
      :saveEmpty="true"
      @callback="selectExportDepotCallBack"
    />

    <!-- <SelectDepot
      v-if="selectStoreDepotInfo.visible"
      v-model:showDialog="selectStoreDepotInfo.visible"
      :checkBox="false"
      :query="selectStoreDepotInfo.query"
      :highlightRow="true"
      :saveEmpty="true"
      @callback="selectStoreDepotCallBack"
    /> -->
    <el-popover
      v-if="selectProductInfo.popoVisible"
      ref="productPopoverRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      :virtual-ref="productRef"
      width="1000px"
      :visible="selectProductInfo.popoVisible"
      virtual-triggering
      @hide="productPopoHide"
    >
      <ProductTable
        v-if="selectProductInfo.popoVisible"
        :popoVisible="selectProductInfo.popoVisible"
        :tableKey="selectProductInfo.tableKey"
        :api="individualInfo.leftApi"
        :query="selectProductInfo.query"
        :highlightRow="selectProductInfo.highlightRow"
        :checkBox="selectProductInfo.checkBox"
        :refresh="selectProductInfo.refresh"
        :showPrice="$permission('consume:price')"
        tableType="product"
        @checkMore="checkMore('product')"
        @reset="selectProductInfo.popoVisible = false"
        @callback="selectProductBack"
        @keyDown="productKeyDown"
      ></ProductTable>
    </el-popover>
    <el-popover
      v-if="selectBatchInfo.popoVisible"
      ref="batchPopoverRef"
      :virtual-ref="batchRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      width="600px"
      :visible="selectBatchInfo.popoVisible"
      virtual-triggering
      @hide="batchPopoHide"
    >
      <ProductTable
        v-if="selectBatchInfo.popoVisible"
        :popoVisible="selectBatchInfo.popoVisible"
        :tableKey="selectBatchInfo.tableKey"
        :query="selectBatchInfo.query"
        :highlightRow="selectBatchInfo.highlightRow"
        :checkBox="selectBatchInfo.checkBox"
        :refresh="selectBatchInfo.refresh"
        :showPrice="$permission('consume:price')"
        :codeType="selectBatchInfo.row.codeType"
        tableType="batch"
        @checkMore="checkMore('batch')"
        @reset="selectBatchInfo.popoVisible = false"
        @callback="selectBatchBack"
        @keyDown="batchKeyDown"
      ></ProductTable>
    </el-popover>
    <BatchIndividual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :leftApi="getConsumeOrderDetailBatchRevokeSingleCustomizeListPage"
      :rightApi="individualInfo.rightApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQuery="individualInfo.leftQuery"
      :rightQuery="individualInfo.rightQuery"
      :details="individualInfo.details"
      :isRequest="individualInfo.isRequest"
      :codeType="individualInfo.codeType"
      :isGetRightList="!!orderId"
      :showPrice="$permission('consume:price')"
      :consumeRevokeDimensionType="formInfo.data.consumeRevokeDimensionType"
      :sysGroup="tableInfo.sysGroup"
      @callback="individualCallback"
    ></BatchIndividual>
  </div>
</template>

<script setup name="batchConsumeRevoke">
import SelectProduct from "./SelectProduct";
import SelectBatch from "./SelectBatch";
import BatchIndividual from "./BatchIndividual";
import ProductTable from "./ProductTable";
import ScanInputBox from "./ScanInputBox";
import StoreBatchNumberTag from "@/views/stock/components/StoreBatchNumberTag";
import { getCoreSystemConfigAll } from "@/api/core";
import { ElMessage, ElLoading } from "element-plus";
import { exportTemplateExcel } from "@/api/pub.js";
import {
  batchValidateConsumeOrder,
  createConsumeOrder,
  updateConsumeOrder,
  detailConsumeOrder,
  getConsumeOrderDetailCustomizeListAll,
  consumeDetailsScan,
  getConsumeOrderDetailBatchRevokeCustomizeListPage,
  getConsumeOrderDetailBatchRevokeSingleCustomizeListPage,
  batchRevokeSubmit,
  depotStockValidateOptimalValidate,
} from "@/api/stock";
import { getCustomizeSetting } from "@/api/customize";
import moment from "moment";
import _ from "lodash";
import axios from "axios";
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from "@/common/js/dateOperation";
import { setVal, setTabindex } from "@/common/js/base";
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const Tooltip = defineAsyncComponent(() =>
  import("@/components/Tooltip/index")
);
const SetPreference = defineAsyncComponent(() =>
  import("@/components/SetPreference/setPreferenceNoQuery")
);
const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: [String, Number],
  },
  orderId: {
    type: [String, Number],
  },
});
const productPopoverRef = ref();
const productRef = ref();
const batchPopoverRef = ref();
const batchRef = ref();
const formRefs = ref([]);
const systemConfig = ref(proxy.$store.state.permission.systemConfig);
const btnList = ref([{ label: "提交", event: save, show: true }]);
const slipSelectRequest = ref(true);
// table 相关 不同维度  tablekey 不一样
const getCustomizeKey = ref({
  1: "batchConsumeRevokeProductList-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  2: "batchConsumeRevokeBatchNumberList-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  3: "batchConsumeRevokeBatchList-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
});
const getProductCustomizeKey = ref({
  1: "batchConsumeRevokeProductOptional-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  2: "batchConsumeRevokeBatchNumberOptional-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  3: "batchConsumeRevokeBatchOptional-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
});
const getSelectBatchInfoKey = ref({
  1: "batchConsumeRevokeProductOptionalSingle-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  2: "batchConsumeRevokeBatchNumberOptionalSingle-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
  3: "batchConsumeRevokeBatchOptionalSingle-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO",
});
const leftTableKey = ref(
  "batchConsumeRevokeSingleLeft-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO"
);
const rightTableKey = ref(
  "batchConsumeRevokeSingleRight-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO"
);
const keysTable = ref({
  1: [
    "consumeTime",
    "consumeUserName",
    "batchNumber",
    "productionDate",
    "validityDate",
    "storeBatchNumber",
    "supplierName",
    "price",
    "canInvalidQty",
  ],
  2: [
    "consumeTime",
    "consumeUserName",
    "storeBatchNumber",
    "supplierName",
    "price",
    "canInvalidQty",
  ],
  3: ["consumeTime", "consumeUserName", "canInvalidQty"],
});
// spanMethodKeys
const spanMethodKeys = ref({
  1: [
    "groupKey",
    "commonName",
    "productCode",
    "standard",
    "brandName",
    "unitName",
    "codeTypeValue",
    "preInvalidQty",
  ],
  2: [
    "groupKey",
    "productCode",
    "commonName",
    "standard",
    "brandName",
    "unitName",
    "codeTypeValue",
    "batchNumber",
    "productionDate",
    "validityDate",
    "preInvalidQty",
  ],
  3: [
    "groupKey",
    "commonName",
    "productCode",
    "standard",
    "brandName",
    "unitName",
    "codeTypeValue",
    "preInvalidQty",
    "batchNumber",
    "productionDate",
    "validityDate",
    "storeBatchNumber",
    "supplierId",
    "price",
  ],
});
// groupkey
// const groupKeysFilter = ref({
//   1:['orgId','productId'],
//   2:['orgId','productId','productionDate','validityDate','batchNumber'],
//   3:['orgId','productId','productionDate','validityDate','price','storeBatchNumber','supplierId','isConsignBusiness','isEstimationStockBusiness'],
// })
const groupKeysFilter = ref({
  1: [
    "batchNumber",
    "productionDate",
    "validityDate",
    "price",
    "supplierId",
    "storeBatchNumber",
    "isConsignBusiness",
    "isEstimationStockBusiness",
  ],
  2: [
    "price",
    "supplierId",
    "storeBatchNumber",
    "isConsignBusiness",
    "isEstimationStockBusiness",
  ],
  3: [],
});
const bgColor = ref({
  1:[
    'orderNo',
    'consumeTime',
    'consumeUserName',
    'batchNumber',
    'productionDate',
    'validityDate',
    'storeBatchNumber',
    'supplierName',
    'price',
    'canInvalidQty',
    'qty'
  ],
  2:[
    'orderNo',
    'consumeTime',
    'consumeUserName',
    'storeBatchNumber',
    'supplierName',
    'price',
    'canInvalidQty',
    'qty'
  ],
  3:[
    'orderNo',
    'consumeTime',
    'consumeUserName',
    'canInvalidQty',
    'qty'
  ]
})
const scanInfo = reactive({
  api: consumeDetailsScan,
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: {
      depotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            "1"
          ) !== -1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ""
        : "",
      consumeDeptId: proxy.$store.state.user.userInfo.dept
        ? proxy.$store.state.user.userInfo.dept.id
        : "",
      groupField: '',
      isDepotSearchRight: 1
      // validateExpire: false
    },
  },
});
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: "slot", value: "addProduct" },
    { type: "slot", value: "removeProduct" },
    { type: "slot", value: "productCodeScan" },
    {
      type: "button",
      label: "下载模板",
      event: downloadTemplate,
      show: proxy.$permission("batchConsumeRevoke:downloadTemplate"),
    },
    {
      type: "slot",
      label: "导入模板",
      value: "uploadExcel",
      show: proxy.$permission("batchConsumeRevoke:upload"),
    },
  ],
});
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  data: [
    {
      emptyRowType: "1", //1添加产品和批次，2添加批次
      productKeyword: "",
      batchKeyword: "",
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  summaryFieldList: [
    { value: "qty", formatter: proxy.$fn.qtyFormatter },
    { value: "sumAmount", formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  // fieldList: [
  //   {
  //     label: '产品编码',
  //     value: 'productCode',
  //     type: 'slot',
  //     minWidth: '100px',
  //   },
  //   {
  //     label: '通用名称',
  //     value: 'commonName',
  //   },
  //   {
  //     label: '规格',
  //     value: 'standard',
  //   },
  //   {
  //     label: '厂家',
  //     value: 'brandName',
  //     width: '80px',
  //   },
  //   {
  //     label: '计量单位',
  //     value: 'unitName',
  //     width: '80px',
  //   },
  //   {
  //     label: '条码类型',
  //     value: 'codeTypeValue',
  //   },
  //   {
  //     label: '预撤回数量',
  //     value: 'preInvalidQty',
  //   },
  //   // span-methods 分界线

  //   {
  //     label: '消耗单号',
  //     value: 'orderNo',
  //     type: 'slot',
  //     align: 'left',
  //     minWidth: '100px',
  //   },
  //   {
  //     label: '消耗时间',
  //     value: 'consumeTime',
  //   },
  //   {
  //     label: '消耗人',
  //     value: 'consumeUserName',
  //   },
  //   {
  //     label: '生产批号',
  //     value: 'batchNumber',
  //   },
  //   {
  //     label: '生产日期',
  //     value: 'productionDate',
  //     width: '80px',
  //   },
  //   {
  //     label: '失效日期',
  //     value: 'validityDate',
  //     width: '80px',
  //   },
  //   {
  //     label: '入库批次号',
  //     value: 'storeBatchNumber',

  //   },
  //   {
  //     label: '供应商',
  //     value: 'supplierName',
  //   },
  //   {
  //     label: '单价',
  //     value: 'price',
  //     type: 'column',
  //     formatter: proxy.$fn.TripartiteMethod,
  //     permission: !proxy.$permission('consume:price'),
  //     width: '60px',
  //   },
  //   {
  //     label: '可撤回数量',
  //     value: 'canInvalidQty',
  //     type: 'column',
  //     formatter: proxy.$fn.qtyFormatter,
  //     width: '60px',
  //   },
  //   {
  //     label: '实际撤回数量',
  //     value: 'invalidQty',
  //     type: 'slot',
  //   },
  //   // {
  //   //   label: '可用数',
  //   //   value: 'canInvalidQty',
  //   //   type: 'column',
  //   //   formatter: proxy.$fn.qtyFormatter,
  //   //   width: '60px',
  //   // },
  //   // {
  //   //   label: '消耗数量',
  //   //   value: 'qty',
  //   //   type: 'slot',
  //   // },
  //   // {
  //   //   label: '消耗金额',
  //   //   value: 'sumAmount',
  //   //   type: 'column',
  //   //   formatter: proxy.$fn.TripartiteMethod,
  //   //   permission: !proxy.$permission('consume:price'),
  //   //   width: '80px',
  //   // },
  // ],
  handle: {
    fixed: "right",
    label: "批次操作",
    width: "100",
    btList: [
      {
        label: "个体详情",
        event: individualDetails,
        show: true,
        ifRender: function (row) {
          let arr = [2, 3];
          return arr.includes(Number(row.codeType)) && row.emptyRowType !== "1";
        },
      },
      {
        label: "新增",
        event: addBucth,
        show: true,
        ifRender: ifRenderAddButch,
      },
      {
        label: "删除",
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return !row.emptyRowType;
        },
      },
    ],
  },
  bigWidth: {
    productCode: "100px",
    standard: "60px",
    brandName: "80px",
    unitName: "80px",
    batchNumber: "100px",
    productionDate: "80px",
    validityDate: "80px",
    supplierName: "80px",
    price: "80px",
    canInvalidQty: "60px",
    qty: "140px",
    sumAmount: "80px",
  },
  smallWidth: {
    productCode: "90px",
    standard: "60px",
    brandName: "60px",
    unitName: "40px",
    batchNumber: "60px",
    productionDate: "50px",
    validityDate: "80px",
    supplierName: "60px",
    price: "50px",
    canInvalidQty: "50px",
    qty: "90px",
    sumAmount: "70px",
  },
});
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          "1"
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ""
      : "",
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          "1"
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ""
      : "",
    // consumeDeptName: "",
    // consumeDeptId: "",
    consumeDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : "",
    consumeDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : "",

    consumeRevokeDimensionType: "1",
  },
  fieldList: [
    {
      label: "消耗撤回维度",
      value: "consumeRevokeDimensionType",
      type: "select-model",
      code: "consume_revoke_dimension_type",
      checkDefault: true,
      required: true,
    },
    // {
    //   label: '出库部门',
    //   value: 'consumeDeptName',
    //   type: 'input',
    //   placeholder: '出库部门',
    //   disabled: true,
    // },
    {
      label: "消耗撤回部门",
      value: "consumeDeptName",
      type: "slot",
    },
    {
      label: "业务日期",
      value: "businessDate",
      type: "date",
      clearable: false,
    },
    { label: "原出库仓库", value: "depotName", type: "slot" },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择原出库仓库', trigger: 'change' }],
    consumeRevokeDimensionType: [
      { required: true, message: "请选择消耗撤回维度", trigger: "change" },
    ],
    consumeDeptName: [
      { required: true, message: "请选择消耗撤回部门", trigger: "change" },
    ],
    businessDate: [
      { required: true, message: "请选择业务日期", target: "blur" },
    ],
  },
  labelWidth: "120px",
});
// end
const uploadInfo = ref({
  action: axios.defaults.baseURL + "/stock/consumeDetails/import/excel",
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          "1"
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ""
      : "",
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          "1"
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ""
      : "",
    consumeDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : "",
    consumeDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : "",
    consumeRevokeDimensionType: "1",
    groupField: '',
    isDepotSearchRight: 1,
    customizeVO: JSON.stringify({}),
    list: JSON.stringify([]),
    // <!-- R37|CP000976|GYS416|OS0000000217|||| -->
  },
  loading: {},
});
const selectProductInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    excludeQueryList: [],
    queryMap: {
      depotId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.coreResourcesVO
          ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
              "1"
            ) !== -1
            ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
            : ""
          : "",
      },
      consumeDeptId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.dept
        ? proxy.$store.state.user.userInfo.dept.id
        : "",
      },
      isConsignBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      productKeyWord: {
        queryType: "ALL_LIKE",
        value: "",
      },
    },
    //isEstimationStockBusiness 这个需要传，如果不传会过滤掉暂估库存
    queryParams: {
      isSelectRevocable: 1,
      // isDepotSearchLeft: 1,
      // stockSearchKey: '',
      // isEstimationStockBusiness: 1,
    },
  },
  // 通用名称搜索
  tableKey:
    getProductCustomizeKey.value[formInfo.data.consumeRevokeDimensionType / 1],
  highlightRow: true,
  checkBox: false,
});
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    queryMap: {
      depotId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.coreResourcesVO
          ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
              "1"
            ) !== -1
            ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
            : ""
          : "",
      },
      consumeDeptId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value:proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : "",
      },
      orgId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
      productId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
      batchNumber: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      id: {
        queryType: "NOT_IN",
        queryCategory: "AND",
        value: null,
      },
      isConsignBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      orderNo: {
        queryType: "ALL_LIKE",
        value: "",
      },
    },
    queryParams: {
      isDepotSearchRight: 1,
      // stockSearchKey: '',
      // groupField: '',
      // isEstimationStockBusiness: 1,
      isSelectRevocable: 1,
    },
  },
  // 新增操作搜索
  tableKey:
    getSelectBatchInfoKey.value[formInfo.data.consumeRevokeDimensionType / 1],
  highlightRow: true,
  checkBox: false,
});
// const selectStoreDepotInfo = reactive({
//   visible: false,
//   query: {
//     depotAuth: 'id',
//     useTypeId: '1',
//     status: 1,
//   },
// })
const selectExportDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: "id",
    useTypeId: "1",
    status: 1,
    isCargoSpaceManage: 0,
  },
});
const individualInfo = ref({
  visible: false,
  codeType: "",
  isRequest: false,
  row: {},
  details: [],
  rightVo: {},
  index: "",
  leftQuery: {
    queryMap: {
      id: {
        queryType: "NOT_IN",
        queryCategory: "AND",
        value: null,
      },
      orgId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
      productId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
      batchNumber: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: "EQUALS",
        queryCategory: "AND",
        ignoreEmptyValue: false,
        value: null,
      },
      depotId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.coreResourcesVO
          ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
              "1"
            ) !== -1
            ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
            : ""
          : "",
      },
      isConsignBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      isEstimationStockBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      consumeDeptId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : "",
      },
    },
    queryParams: {
      isDepotSearchRight: 1,
      groupField: "",
      // isEstimationStockBusiness: 1,
      isSelectRevocable: 1,
    },
  }, //个体弹窗左边数据查询条件
  rightQuery: {
    queryMap: {
      isConsignBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      isEstimationStockBusiness: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "",
      },
      id: {
        queryType: "IN",
        queryCategory: "AND",
        value: null,
      },
      orderId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: null,
      },
      depotId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: proxy.$store.state.user.userInfo.coreResourcesVO
          ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
              "1"
            ) !== -1
            ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
            : ""
          : "",
      },
    },
    queryParams: {},
  }, //个体弹窗右边数据查询条件
  leftTableKey: leftTableKey.value,
  rightTableKey: rightTableKey.value,
  rightApi: getConsumeOrderDetailCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getConsumeOrderDetailBatchRevokeCustomizeListPage, //个体弹窗左边数据接口
});

const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: "id",
    status: "1",
  },
});
let disStartDate = ref("");
let disEndDate = ref("");
const showDialog = computed({
  get() {
    return props.visible;
  },
  set(newValue) {
    emit("update:visible", newValue); // 更新父组件visible
  },
});
const canSave = computed(() => {
  return tableInfo.data.length;
});
const canAddProduct = computed(() => {
  return formInfo.data.consumeDeptId && formInfo.data.depotId
});
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length;
});
// 监听维度变化
watch(
  () => formInfo.data.consumeRevokeDimensionType,
  (val) => {
    uploadInfo.value.data.consumeRevokeDimensionType = val;
    selectProductInfo.value.tableKey =
      getProductCustomizeKey.value[
        formInfo.data.consumeRevokeDimensionType / 1
      ];
    selectBatchInfo.value.tableKey =
      getSelectBatchInfoKey.value[formInfo.data.consumeRevokeDimensionType / 1];
    // 清空表格
    tableInfo.data = [
      {
        emptyRowType: "1", //1添加产品和批次，2添加批次
        productKeyword: "",
        batchKeyword: "",
        id: new Date().getTime() + (1 + Math.random()),
      },
    ];
    getCustomize();
    getScanCustomize();
    getProductCustomize();
  }
);
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      let list = [];
      let groupkeys = []
      tableInfo.data.forEach((item, index) => {
        
        if (item.emptyRowType && item.emptyRowType === "1") {
          let arr = [
            { key: "productKey" + index, index: index },
            { key: "batchKey" + index, index: index },
          ];
          list = list.concat(arr);
        } else if (item.emptyRowType && item.emptyRowType === "2") {
          list.push({ key: "batchKey" + index, index: index });
        }
        let depotStockIds = [];
        let groupConcatId = [];
        if (item.details && item.details.length) {
          depotStockIds = item.details.map((el) => el.depotStockId);
          groupConcatId = item.details.map((el) => el.groupConcatIds);
        } else {
          if (item.groupConcatDepotStockIds) {
            depotStockIds.push(item.groupConcatDepotStockIds);
          }
        }
        item.groupConcatDepotStockIds = depotStockIds.length
          ? depotStockIds.toString()
          : "";
        item.groupConcatIds = groupConcatId.length
          ? groupConcatId.toString()
          : "";
      });
      // 导入背景颜色判
      let groupData = _.groupBy(val, 'groupKey')
      for (const key in groupData) {
        if (groupData.hasOwnProperty.call(groupData, key)) {
          const element = groupData[key];
          let result = 0;
          element.map((i) => {
            result += i.qty;
          });
          console.log(element)
          if (element[0].preInvalidQty > result) {
            groupkeys.push(key)
          }
        }
      }
      console.log(groupkeys)
      tableInfo.data.forEach(item => {
        if(groupkeys.includes(item.groupKey)) {
          item.isLessData = true
        } else {
          item.isLessData = false
        }
      })
      tableInfo.tabList = list;

      setTabindex(proxy);
      setSuplierIdMap();
    }
  },
  { deep: true }
);
watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false;
    }
  }
);
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false;
    }
  }
);

onMounted(() => {
  formRefs.value = [proxy.$refs["tableForm"], formInfo.ref];
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== "orderNo"
      );
    }
  });
  proxy.$fn.setFieldListColWidth(
    tableInfo.fieldList,
    tableInfo.bigWidth,
    tableInfo.smallWidth
  );
});
window.addEventListener("click", closePopper, { passive: true });
window.addEventListener("keydown", addTab, true);
onActivated(() => {
  window.addEventListener("click", closePopper, { passive: true });
  window.addEventListener("keydown", addTab, true);
});
onDeactivated(() => {
  window.removeEventListener("click", closePopper, true);
  window.removeEventListener("keydown", addTab, true);
});

//
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: "系统错误",
      duration: 3000,
      showClose: true,
    });
  }
  uploadInfo.value.loading.close();
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: "rgba(255,255,255,.4)",
  });
  let fileType = ["xlsx", "xls"];
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size;
  let isFileType = fileType.some(
    (type) => file.name.split(".")[file.name.split(".").length - 1] === type
  );
  const isLt = file.size / 1024 / 1024 < fileSize;
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(" / ")} 格式文件!`,
      showClose: true,
      duration: 3500,
    });
    uploadInfo.value.loading.close();
    return false;
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    });
    uploadInfo.value.loading.close();
    return false;
  }
  // 
  let result = []
  tableInfo.data.map((item, index) => {
    if(item.emptyRowType != 1) {
      
      result[index] = {
        codeType: item.codeType,
        productId: item.productId,
        productCode: item.productCode,
        batchNumber: item.batchNumber,
        productionDate: item.productionDate,
        validityDate: item.validityDate,
        supplierId: item.supplierId,
        supplierName: item.supplierName,
        storeBatchNumber: item.storeBatchNumber,
        price: item.price
      }
      // codeType 2 唯一码 传details 其他不传
      if (item.codeType == 2 && item.details && item.details.length) {
        item.details.map((i) => {
          result[index].details = {
            productId: i.productId,
            qrCode: i.qrCode,
            uniqueCode: i.uniqueCode,
            factoryMainCode: i.factoryMainCode,
            factorySubCode: i.factorySubCode,
          }
        });
      }
    }
  });
  console.log(4)
  result = result.filter(i => i)
  uploadInfo.value.data.list = JSON.stringify(result)
  uploadInfo.value.data.customizeVO = JSON.stringify(scanInfo.query)
  return isFileType && isLt;
}
function importProduct(resp) {
  uploadInfo.value.loading.close();
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: "导入成功",
    });
    // 将三级列表 个体信息拼接 为 二级列表
    // 第一步 组建 groupKey  groupRowKey
    let index = selectProductInfo.value.index;
    let keys = keysTable.value[formInfo.data.consumeRevokeDimensionType + ""];
    let data = resp.data;
    let newData =  data.map((row) => {
      // 是否是导入
      row.isExport = true;
      row.canInvalidQty = row.mergeStockAvailableQty || 0
      let str = "";
      tableInfo.sysGroup.forEach((item) => {
        if (
          !groupKeysFilter.value[
            formInfo.data.consumeRevokeDimensionType + ""
          ].includes(item)
        ) {
          if (item === "productionDate" || item === "validityDate") {
            str = str + (row[item] || "1900-01-01") + "";
          } else {
            str = str + row[item] + "";
          }
        }
      });
      // 产品维度  生产批号、生产日期、失效日期、入库批次、供应商、单价、是否暂估、是否寄售
      // 批号维度  入库批次、供应商、单价、是否暂估、是否寄售
      // 批次维度  groupKey + id
      if (formInfo.data.consumeRevokeDimensionType == 1) {
        row._key =
          row.orderNo +
          "-" +
          row.batchNumber +
          "-" +
          row.productionDate +
          "-" +
          row.validityDate +
          "-" +
          row.storeBatchNumber +
          "-" +
          row.supplierId +
          "-" +
          row.price +
          "-" +
          row.isConsignBusiness +
          "-" +
          row.isEstimationStockBusiness;
      }
      if (formInfo.data.consumeRevokeDimensionType == 2) {
        row._key =
          row.orderNo +
          "-" +
          row.storeBatchNumber +
          "-" +
          row.supplierId +
          "-" +
          row.price +
          "-" +
          row.isConsignBusiness +
          "-" +
          row.isEstimationStockBusiness;
      }
      if (formInfo.data.consumeRevokeDimensionType == 3) {
        row._key = row.orderNo;
      }
      row.groupKey = str;
      row.groupRowKey = str + row._key;
      if (row.groupConcatIds && row.groupConcatIds.includes(",")) {
        return {
          commonName: !keys.includes("commonName") ? row.commonName : "",
          productCode: !keys.includes("productCode") ? row.productCode : "",
          groupKey: !keys.includes("groupKey") ? row.groupKey : "",
          standard: !keys.includes("standard") ? row.standard : "",
          brandName: !keys.includes("brandName") ? row.brandName : "",
          brandId: !keys.includes("brandId") ? row.brandId : "",
          unitName: !keys.includes("unitName") ? row.unitName : "",
          unitId: !keys.includes("unitId") ? row.unitId : "",
          codeTypeValue: !keys.includes("codeTypeValue")
            ? row.codeTypeValue
            : "",
          codeType: !keys.includes("codeType") ? row.codeType : "",
          batchNumber: !keys.includes("batchNumber") ? row.batchNumber : "",
          productionDate: !keys.includes("productionDate")
            ? row.productionDate
            : "",
          validityDate: !keys.includes("validityDate") ? row.validityDate : "",
          depotStockId: !keys.includes("depotStockId") ? row.depotStockId : "",
          productId: !keys.includes("productId") ? row.productId : "",
          storeBatchNumber: !keys.includes("storeBatchNumber")
            ? row.storeBatchNumber
            : "",
          supplierName: !keys.includes("supplierName") ? row.supplierName : "",
          supplierId: !keys.includes("supplierId") ? row.supplierId : "",
          price: !keys.includes("price") ? row.price : "",
          orgId: !keys.includes("orgId") ? row.orgId : "",
          productId: !keys.includes("productId") ? row.productId : "",
          isConsignBusiness:
            !keys.includes("isConsignBusiness") &&
            formInfo.data.consumeRevokeDimensionType == 3
              ? row.isConsignBusiness
              : "",
          isEstimationStockBusiness:
            !keys.includes("isEstimationStockBusiness") &&
            formInfo.data.consumeRevokeDimensionType == 3
              ? row.isEstimationStockBusiness
              : "",
          emptyRowType: "2",
        };
      } else {
        row = countData(row);
        if(!(row.details && row.details.length)){
          row.details = [proxy.$fn.deepClone(row)];
        }
        return row;
      }
    });
    let emptyRowTypeList = tableInfo.data.filter(
      (item) => item.emptyRowType === "1"
    ); //空行条数
    let list = proxy.$fn.deepClone(tableInfo.data);
    let leftList,
      rightList = [];
    if (emptyRowTypeList.length > 1) {
      if (index === tableInfo.data.length - 1) {
        //是否最后一条
        leftList = list.slice(0, index);
        rightList = list.slice(index);
      } else {
        leftList = list.slice(0, index);
        rightList = list.slice(index + 1);
      }
    } else {
      leftList = list.slice(0, index);
      rightList = list.slice(index);
    }
    // tableInfo.data = leftList.concat(newData).concat(rightList);
    // let result = leftList.concat(newData).concat(rightList)
    let groupData = _.groupBy(newData, 'groupRowKey')
    let groupDataKeys = Object.keys(groupData)
    let arr = []
    groupDataKeys.forEach((key) => {
      let list = groupData[key]
      console.log(list)
      let item = list[0]
      if(item.isExport) {
        item.details = proxy.$fn.deepClone(list)
      } else if(!(item.details && item.details.length) ){
        item.details = proxy.$fn.deepClone(list)
      }
      arr.push(item)
    })
    arr.forEach((row) => {
      let largeUnitQty = 0
      let smallUnitQty = 0
      let calcQty = 0
      let sumAmount = 0
      let stockAvailableCalcQty = 0
      let stockAvailableQty = 0
      row.details.forEach((item) => {
        calcQty = proxy.$fn.accAdd(item.calcQty || 0, calcQty)
        largeUnitQty = proxy.$fn.accAdd(
          item.largeUnitQty || 0,
          largeUnitQty
        )
        smallUnitQty = proxy.$fn.accAdd(
          item.smallUnitQty || 0,
          smallUnitQty
        )
        sumAmount = proxy.$fn.accAdd(item.sumAmount || 0, sumAmount)
        stockAvailableCalcQty = proxy.$fn.accAdd(
          item.stockAvailableCalcQty || 0,
          stockAvailableCalcQty
        )
        stockAvailableQty = proxy.$fn.accAdd(
          item.stockAvailableQty || 0,
          stockAvailableQty
        )
      })
      row.largeUnitQty = largeUnitQty
      row.smallUnitQty = smallUnitQty
      row.calcQty = calcQty
      row.qty = proxy.$fn.accDiv(calcQty, row.unitConvertCoefficient || 1)
      row.sumAmount = sumAmount
      row.stockAvailableCalcQty = stockAvailableCalcQty
      row.stockAvailableQty = stockAvailableQty
    })
    let result = leftList.concat(arr).concat(rightList)
    result = mapArray(result)
    tableInfo.data = result
    let itemList = tableInfo.data.filter((item) => item.emptyRowType === "1");
    if (!itemList.length) {
      tableInfo.data.push({
        emptyRowType: "1",
        productKeyword: "",
        batchKeyword: "",
        id: new Date().getTime() + (1 + Math.random()),
      });
    }
    console.log(tableInfo.data)
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    });
  }
}
//处理数组的方法
function mapArray(arr) {
  let keys = arr.map((val) => {
    return val.groupKey;
  });
  //数组去重，这样就得到了一共有多少个key
  keys = [...new Set(keys)];
  //声明一个target来装数组
  let target = [];
  //如果key值相等，则push到同一个数组
  keys.some((value) => {
    arr.map((val) => {
      if (val.groupKey == value) {
        target.push(val);
        return;
      }
    });
  });
  return target
}


function downloadTemplate() {
  exportTemplateExcel("consume_order_revoke_import").then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res);
    }
  });
}
function addTab(val) {
  if (val.key === "Tab") {
    if (!canAddProduct.value) {
      selectExportDepot();
      return;
    }
  }
}
setDisableTime(formInfo.fieldList, disStartDate, disEndDate);
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  );
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data.consumeDeptName = row.name;
    formInfo.data.consumeDeptId = row.id;
    uploadInfo.value.data.consumeDeptName = row.name;
    uploadInfo.value.data.consumeDeptId = row.id;
    selectProductInfo.value.query.queryMap.consumeDeptId.value = row.id;
    individualInfo.value.leftQuery.queryMap.consumeDeptId.value = row.id;
    scanInfo.query.queryParams.consumeDeptId = row.id;
    selectBatchInfo.value.query.queryMap.consumeDeptId.value = row.id;
  } else {
    formInfo.data.consumeDeptName = "";
    formInfo.data.consumeDeptId = "";
    uploadInfo.value.data.consumeDeptName = "";
    uploadInfo.value.data.consumeDeptId = "";
    selectProductInfo.value.query.queryMap.consumeDeptId.value = "";
    individualInfo.value.leftQuery.queryMap.consumeDeptId.value = "";
    selectBatchInfo.value.query.queryMap.consumeDeptId.value = "";
    scanInfo.query.queryParams.consumeDeptId = "";
  }
}
function closePopper(e) {
  if (
    e.target.closest(".el-popper") ||
    e.target.closest(".productKey") ||
    e.target.closest(".batchKey")
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false;
    selectProductInfo.value.popoVisible = false;
  }
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.fieldList.length;
  if (row.emptyRowType !== "1" || !row.emptyRowType) {
    const afterIndexs = row.codeType == 2 || row.codeType == 3 ? [len + 1] : [];
    let keys = new Array(len + 2);
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = "groupKey";
    } else {
      keys =
        spanMethodKeys.value[formInfo.data.consumeRevokeDimensionType + ""];
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(tableInfo.data, keys, rowIndex, columnIndex);
  }
}
function ifRenderAddButch(row) {
  let arr = [1, 4];
  if (arr.includes(row.codeType)) {
    let list = tableInfo.data.filter((item) => item.groupKey === row.groupKey);
    let index = list.findIndex((item) => item._key === row._key);
    return index === list.length - 1;
  }
}
//新增行
function addProduct() {
  tableInfo.data.push({
    emptyRowType: "1",
    productKeyword: "",
    batchKeyword: "",
    id: new Date().getTime() + (1 + Math.random()),
  });
}
function checkMore(str) {
  if (str === "product") {
    let row = selectProductInfo.value.row;
    let index = selectProductInfo.value.index;
    productSearch(row, index);
  } else if (str === "batch") {
    let row = selectBatchInfo.value.row;
    let index = selectBatchInfo.value.index;
    batchNumberSearch(row, index);
  }
}
function productSearch(row, index) {
  //产品点击查询图标
  if (!canAddProduct.value) {
    // selectExportDepot()
    return;
  }
  selectProductInfo.value.query.queryMap.productKeyWord.value = row.productKeyword
  selectProductInfo.value.row = row;
  selectProductInfo.value.index = index;
  let key = [];
  tableInfo.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === "2") {
      let arr = [];
      tableInfo.productSysGroup.forEach((item) => {
        let obj = {};
        obj.columnName = item.columnName;
        obj.asTbName = item.asTbName;
        obj.value = row[item.key];
        arr.push(obj);
      });
      key.push(arr);
    }
  });
  selectProductInfo.value.query.excludeQueryList = key;
  selectProductInfo.value.visible = true;
  selectProductInfo.value.popoVisible = false;
}

function productSearchInput(row, index) {
  //产品enter查询
  if (!canAddProduct.value) {
    // selectExportDepot()
    return;
  }
  productRef.value = proxy.$refs["productRef" + index];
  selectProductInfo.value.query.queryMap.productKeyWord.value = row.productKeyword
  selectProductInfo.value.refresh = Math.random();
  selectProductInfo.value.row = row;
  selectProductInfo.value.index = index;
  let key = [];
  tableInfo.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === "2") {
      let arr = [];
      tableInfo.productSysGroup.forEach((item) => {
        let obj = {};
        obj.columnName = item.columnName;
        obj.asTbName = item.asTbName;
        obj.value = row[item.key];
        arr.push(obj);
      });
      key.push(arr);
    }
  });
  selectProductInfo.value.query.excludeQueryList = key;
  selectProductInfo.value.popoVisible = true;
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = "productKey" + selectProductInfo.value.index;
      setVal(className);
      selectProductInfo.value.popoVisible = false;
      return;
    }
    let className = "productKey" + selectProductInfo.value.index;
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector(".el-input__inner");
    productKeyDom.blur();
  });
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index;
  let keys = keysTable.value[formInfo.data.consumeRevokeDimensionType + ""];
  if (obj.groupConcatIds.includes(",")) {
    tableInfo.data[index] = {
      commonName: !keys.includes("commonName") ? obj.commonName : "",
      productCode: !keys.includes("productCode") ? obj.productCode : "",
      groupKey: !keys.includes("groupKey") ? obj.groupKey : "",
      standard: !keys.includes("standard") ? obj.standard : "",
      brandName: !keys.includes("brandName") ? obj.brandName : "",
      brandId: !keys.includes("brandId") ? obj.brandId : "",
      unitName: !keys.includes("unitName") ? obj.unitName : "",
      unitId: !keys.includes("unitId") ? obj.unitId : "",
      codeTypeValue: !keys.includes("codeTypeValue") ? obj.codeTypeValue : "",
      codeType: !keys.includes("codeType") ? obj.codeType : "",
      batchNumber: !keys.includes("batchNumber") ? obj.batchNumber : "",
      productionDate: !keys.includes("productionDate")
        ? obj.productionDate
        : "",
      validityDate: !keys.includes("validityDate") ? obj.validityDate : "",
      depotStockId: !keys.includes("depotStockId") ? obj.depotStockId : "",
      storeBatchNumber: !keys.includes("storeBatchNumber")
        ? obj.storeBatchNumber
        : "",
      supplierName: !keys.includes("supplierName") ? obj.supplierName : "",
      supplierId: !keys.includes("supplierId") ? obj.supplierId : "",
      price: !keys.includes("price") ? obj.price : "",
      orgId: !keys.includes("orgId") ? obj.orgId : "",
      productId: !keys.includes("productId") ? obj.productId : "",
      isConsignBusiness:
        !keys.includes("isConsignBusiness") &&
        formInfo.data.consumeRevokeDimensionType == 3
          ? obj.isConsignBusiness
          : "",
      isEstimationStockBusiness:
        !keys.includes("isEstimationStockBusiness") &&
        formInfo.data.consumeRevokeDimensionType == 3
          ? obj.isEstimationStockBusiness
          : "",
      emptyRowType: "2",
    };
    // if (obj.codeType === 1 || obj.codeType === 4) {
    //   batchNumberSearchInput(tableInfo.data[index], index)
    // } else if (obj.codeType === 2 || obj.codeType === 3) {
    //   batchNumberSearch(tableInfo.data[index], index)
    // }
  } else {
    // keys.map((i) => {
    //   obj.emptyRowType = "2";
    //   if (obj[i]) {
    //     delete obj[i];
    //   }
    // });
    obj = countData(obj);
    tableInfo.data[index] = proxy.$fn.deepClone(obj);
    tableInfo.data[index].details = [proxy.$fn.deepClone(obj)];
  }
  let itemList = tableInfo.data.filter((item) => item.emptyRowType === "1");
  if (!itemList.length) {
    tableInfo.data.push({
      emptyRowType: "1",
      productKeyword: "",
      batchKeyword: "",
      id: new Date().getTime() + (1 + Math.random()),
    });
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index;
  // 不同维度 有的不获取值
  let keys = keysTable.value[formInfo.data.consumeRevokeDimensionType + ""];
  let newData = data.map((item) => {
    let str = "";
    tableInfo.sysGroup.forEach((i) => {
      if (
        !groupKeysFilter.value[
          formInfo.data.consumeRevokeDimensionType + ""
        ].includes(i)
      ) {
        if (i === "productionDate" || i === "validityDate") {
          str = str + (item[i] || "1900-01-01") + "";
        } else {
          str = str + item[i] + "";
        }
      }
    });
    if (formInfo.data.consumeRevokeDimensionType == 1) {
      item._key =
        item.orderNo +
        "-" +
        item.batchNumber +
        "-" +
        item.productionDate +
        "-" +
        item.validityDate +
        "-" +
        item.storeBatchNumber +
        "-" +
        item.supplierId +
        "-" +
        item.price +
        "-" +
        item.isConsignBusiness +
        "-" +
        item.isEstimationStockBusiness;
    }
    if (formInfo.data.consumeRevokeDimensionType == 2) {
      item._key =
        item.orderNo +
        "-" +
        item.storeBatchNumber +
        "-" +
        item.supplierId +
        "-" +
        item.price +
        "-" +
        item.isConsignBusiness +
        "-" +
        item.isEstimationStockBusiness;
    }
    if (formInfo.data.consumeRevokeDimensionType == 3) {
      item._key = item.orderNo;
    }
    item.groupKey = str;
    item.groupRowKey = str + item._key;
    if (item.groupConcatIds && item.groupConcatIds.includes(",")) {
      return {
        commonName: !keys.includes("commonName") ? item.commonName : "",
        productCode: !keys.includes("productCode") ? item.productCode : "",
        groupKey: !keys.includes("groupKey") ? item.groupKey : "",
        standard: !keys.includes("standard") ? item.standard : "",
        brandName: !keys.includes("brandName") ? item.brandName : "",
        brandId: !keys.includes("brandId") ? item.brandId : "",
        unitName: !keys.includes("unitName") ? item.unitName : "",
        unitId: !keys.includes("unitId") ? item.unitId : "",
        codeTypeValue: !keys.includes("codeTypeValue")
          ? item.codeTypeValue
          : "",
        codeType: !keys.includes("codeType") ? item.codeType : "",
        batchNumber: !keys.includes("batchNumber") ? item.batchNumber : "",
        productionDate: !keys.includes("productionDate")
          ? item.productionDate
          : "",
        validityDate: !keys.includes("validityDate") ? item.validityDate : "",
        depotStockId: !keys.includes("depotStockId") ? item.depotStockId : "",
        productId: !keys.includes("productId") ? item.productId : "",
        storeBatchNumber: !keys.includes("storeBatchNumber")
          ? item.storeBatchNumber
          : "",
        supplierName: !keys.includes("supplierName") ? item.supplierName : "",
        supplierId: !keys.includes("supplierId") ? item.supplierId : "",
        price: !keys.includes("price") ? item.price : "",
        orgId: !keys.includes("orgId") ? item.orgId : "",
        productId: !keys.includes("productId") ? item.productId : "",
        isConsignBusiness:
          !keys.includes("isConsignBusiness") &&
          formInfo.data.consumeRevokeDimensionType == 3
            ? item.isConsignBusiness
            : "",
        isEstimationStockBusiness:
          !keys.includes("isEstimationStockBusiness") &&
          formInfo.data.consumeRevokeDimensionType == 3
            ? item.isEstimationStockBusiness
            : "",
        emptyRowType: "2",
      };
    } else {
      // keys.map((i) => {
      //   item.emptyRowType = "2";
      //   if (item[i]) {
      //     delete item[i];
      //     // item[i] = ''
      //   }
      // });
      item = countData(item);
      item.details = [proxy.$fn.deepClone(item)];
      return item;
    }
  });
  let emptyRowTypeList = tableInfo.data.filter(
    (item) => item.emptyRowType === "1"
  ); //空行条数
  let list = proxy.$fn.deepClone(tableInfo.data);
  let leftList,
    rightList = [];
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index);
      rightList = list.slice(index);
    } else {
      leftList = list.slice(0, index);
      rightList = list.slice(index + 1);
    }
  } else {
    leftList = list.slice(0, index);
    rightList = list.slice(index);
  }
  tableInfo.data = leftList.concat(newData).concat(rightList);
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false;
}
function batchNumberSearch(row, index) {
  //批次点击查询图标
  if (!row.depotStockId) return;
  selectBatchInfo.value.query.queryMap.orderNo.value = row.batchKeyword;
  selectBatchInfo.value.row = row;
  selectBatchInfo.value.index = index;
  let list = tableInfo.data.filter((item) => item.groupKey === row.groupKey);
  let ids = [];
  if (list.length) {
    list.forEach((row) => {
      if (row.id) {
        ids.push(row.id);
      }
      // if (row.groupConcatDepotStockIds) {
      //   ids.push(row.groupConcatDepotStockIds)
      // }
    });
  }
  selectBatchInfo.value.query.queryMap.orgId.value = row.orgId;
  selectBatchInfo.value.query.queryMap.productId.value = row.productId;
  // 产品维度 不加batchNumber validityDate productionDate
  if (formInfo.data.consumeRevokeDimensionType != 1) {
    if (row.batchNumber) {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.batchNumber,
      };
    } else {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: "NULL",
        queryCategory: "AND",
        value: "",
      };
    }
    if (row.validityDate) {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.validityDate,
      };
    } else {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: "NULL",
        ignoreEmptyValue: false,
        queryCategory: "AND",
        value: null,
      };
    }
    if (row.productionDate) {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.productionDate,
      };
    } else {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: "NULL",
        ignoreEmptyValue: false,
        queryCategory: "AND",
        value: null,
      };
    }
  } else {
    delete selectBatchInfo.value.query.queryMap.batchNumber;
    delete selectBatchInfo.value.query.queryMap.validityDate;
    delete selectBatchInfo.value.query.queryMap.productionDate;
  }
  if (formInfo.data.consumeRevokeDimensionType == 3) {
    selectBatchInfo.value.query.queryMap.storeBatchNumber = {
      queryType: "EQUALS",
      value: row.storeBatchNumber,
    };
    selectBatchInfo.value.query.queryMap.isConsignBusiness = {
      queryType: "EQUALS",
      value: row.isConsignBusiness,
    };
    selectBatchInfo.value.query.queryMap.isEstimationStockBusiness = {
      queryType: "EQUALS",
      value: row.isEstimationStockBusiness,
    };
    selectBatchInfo.value.query.queryMap.supplierId = {
      queryType: "EQUALS",
      value: row.supplierId,
    };
    selectBatchInfo.value.query.queryMap.price = {
      queryType: "EQUALS",
      value: row.price,
    };
  } else {
    delete selectBatchInfo.value.query.queryMap.storeBatchNumber;
    delete selectBatchInfo.value.query.queryMap.isConsignBusiness;
    delete selectBatchInfo.value.query.queryMap.isEstimationStockBusiness;
    delete selectBatchInfo.value.query.queryMap.supplierId;
    delete selectBatchInfo.value.query.queryMap.price;
  }
  // selectBatchInfo.value.query.queryMap.batchNumber.value = row.batchNumber || ''
  // selectBatchInfo.value.query.queryMap.validityDate.value =
  //   row.validityDate || ''
  // selectBatchInfo.value.query.queryMap.productionDate.value =
  //   row.productionDate || ''
  if (row.details && row.details.length >= 1) {
    selectBatchInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : "";
  } else {
    selectBatchInfo.value.query.queryMap.id.value = "";
  }
  selectBatchInfo.value.visible = true;
  selectBatchInfo.value.popoVisible = false;
}
function batchNumberSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    if (!row.depotStockId) return;

    let className = "batchKey" + index;
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector(".el-input__inner");
    batchKeyDom.focus();
    batchRef.value = proxy.$refs["batchRef" + index];
    selectBatchInfo.value.query.queryMap.orderNo.value = row.batchKeyword;
    selectBatchInfo.value.refresh = Math.random();
    selectBatchInfo.value.row = row;
    selectBatchInfo.value.index = index;
    let list = tableInfo.data.filter((item) => item.groupKey === row.groupKey);
    let ids = [];
    if (list.length) {
      list.forEach((row) => {
        if (row.id) {
          ids.push(row.id);
        }
        // if (row.groupConcatDepotStockIds) {
        //   ids.push(item.groupConcatDepotStockIds)
        // }
      });
    }
    selectBatchInfo.value.query.queryMap.orgId.value = row.orgId;
    selectBatchInfo.value.query.queryMap.productId.value = row.productId;

    if (formInfo.data.consumeRevokeDimensionType != 1) {
      if (row.batchNumber) {
        selectBatchInfo.value.query.queryMap.batchNumber = {
          queryType: "EQUALS",
          queryCategory: "AND",
          value: row.batchNumber,
        };
      } else {
        selectBatchInfo.value.query.queryMap.batchNumber = {
          queryType: "NULL",
          queryCategory: "AND",
          value: null,
        };
      }
      if (row.validityDate) {
        selectBatchInfo.value.query.queryMap.validityDate = {
          queryType: "EQUALS",
          queryCategory: "AND",
          value: row.validityDate,
        };
      } else {
        selectBatchInfo.value.query.queryMap.validityDate = {
          queryType: "NULL",
          ignoreEmptyValue: false,
          queryCategory: "AND",
          value: null,
        };
      }
      if (row.productionDate) {
        selectBatchInfo.value.query.queryMap.productionDate = {
          queryType: "EQUALS",
          queryCategory: "AND",
          value: row.productionDate,
        };
      } else {
        selectBatchInfo.value.query.queryMap.productionDate = {
          queryType: "NULL",
          ignoreEmptyValue: false,
          queryCategory: "AND",
          value: null,
        };
      }
    } else {
      delete selectBatchInfo.value.query.queryMap.batchNumber;
      delete selectBatchInfo.value.query.queryMap.validityDate;
      delete selectBatchInfo.value.query.queryMap.productionDate;
    }
    if (formInfo.data.consumeRevokeDimensionType == 3) {
      selectBatchInfo.value.query.queryMap.storeBatchNumber = {
        queryType: "EQUALS",
        value: row.storeBatchNumber,
      };
      selectBatchInfo.value.query.queryMap.isConsignBusiness = {
        queryType: "EQUALS",
        value: row.isConsignBusiness,
      };
      selectBatchInfo.value.query.queryMap.isEstimationStockBusiness = {
        queryType: "EQUALS",
        value: row.isEstimationStockBusiness,
      };
      selectBatchInfo.value.query.queryMap.supplierId = {
        queryType: "EQUALS",
        value: row.supplierId,
      };
      selectBatchInfo.value.query.queryMap.price = {
        queryType: "EQUALS",
        value: row.price,
      };
    } else {
      delete selectBatchInfo.value.query.queryMap.storeBatchNumber;
      delete selectBatchInfo.value.query.queryMap.isConsignBusiness;
      delete selectBatchInfo.value.query.queryMap.isEstimationStockBusiness;
      delete selectBatchInfo.value.query.queryMap.supplierId;
      delete selectBatchInfo.value.query.queryMap.price;
    }
    // selectBatchInfo.value.query.queryMap.batchNumber.value =
    //   row.batchNumber || ''
    // selectBatchInfo.value.query.queryMap.validityDate.value =
    //   row.validityDate || ''
    // selectBatchInfo.value.query.queryMap.productionDate.value =
    //   row.productionDate || ''
    if (row.details && row.details.length >= 1) {
      selectBatchInfo.value.query.queryMap.id.value = ids.length
        ? ids.toString()
        : "";
    } else {
      selectBatchInfo.value.query.queryMap.id.value = "";
    }
    selectBatchInfo.value.popoVisible = true;
    clearTimeout(timer);
  }, 0);
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false;
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index;
  let row = selectBatchInfo.value.row;
  let data = proxy.$fn.deepClone(tableInfo.data[index]);
  obj = countData(obj);
  obj.canInvalidQty = obj.mergeStockAvailableQty || 0;
  obj.canInvalidCalcQty = obj.mergeStockAvailableCalcQty || 0;
  tableInfo.data[index] = proxy.$fn.deepClone(obj);
  tableInfo.data[index].details = [proxy.$fn.deepClone(obj)];
  tableInfo.data[index].groupKey = data.groupKey;
}
function selectBatchBackList(data) {
  let row = selectBatchInfo.value.row;
  let index = selectBatchInfo.value.index;
  data.forEach((item) => {
    item = countData(item);
  });
  let groupData = _.groupBy(data, "_key");
  let groupKeys = Object.keys(groupData);
  let groupKeysIn = [];
  tableInfo.data.forEach((item) => {
    if (item.groupKey === row.groupKey) {
      if (item._key) {
        if (groupKeys.includes(item._key)) {
          groupKeysIn.push(item._key);
          item.details = item.details.concat(groupData[item._key]);
          item = countQty(item);
        }
      }
    }
  });
  let list = [];
  if (groupKeysIn.length) {
    groupKeys.forEach((item) => {
      if (!groupKeysIn.includes(item)) {
        let groupDataItem = groupData[item];
        let obj = proxy.$fn.deepClone(groupDataItem[0]);
        obj.details = proxy.$fn.deepClone(groupDataItem);
        obj.groupKey = row.groupKey;
        obj = countQty(obj);
        obj.canInvalidQty = obj.mergeStockAvailableQty || 0;
        obj.canInvalidCalcQty = obj.mergeStockAvailableCalcQty || 0;
        list.push(obj);
      }
    });
  } else {
    let values = Object.values(groupData);
    values.forEach((item) => {
      let obj = proxy.$fn.deepClone(item[0]);
      obj.details = proxy.$fn.deepClone(item);
      obj.groupKey = row.groupKey;
      obj = countQty(obj);
      obj.canInvalidQty = obj.mergeStockAvailableQty || 0;
      obj.canInvalidCalcQty = obj.mergeStockAvailableCalcQty || 0;
      list.push(obj);
    });
  }
  if (list.length) {
    let newData = tableInfo.data[index];
    let leftList = [];
    if (newData._key) {
      leftList = tableInfo.data.slice(0, index + 1);
    } else {
      leftList = tableInfo.data.slice(0, index);
    }
    let rightList = tableInfo.data.slice(index + 1);
    tableInfo.data = leftList.concat(list).concat(rightList);
  }
}
function countQty(data) {
  let largeUnitQty = 0;
  let smallUnitQty = 0;
  let calcQty = 0;
  let qty = 0;
  data.details.forEach((el) => {
    largeUnitQty = proxy.$fn.accAdd(largeUnitQty, el.largeUnitQty || 0);
    smallUnitQty = proxy.$fn.accAdd(smallUnitQty, el.smallUnitQty || 0);
    calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0);

    if (data.codeType === 2 || data.codeType === 3) {
      el.invalidCalcQty = el.calcQty;
      el.invalidQty = proxy.$fn.accDiv(calcQty, el.unitConvertCoefficient || 1);

      el.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, el.price || 0),
        el.unitConvertCoefficient || 1
      );
    }
  });
  data.largeUnitQty = largeUnitQty;
  data.smallUnitQty = smallUnitQty;
  data.calcQty = calcQty;
  data.qty = proxy.$fn.accDiv(calcQty, data.unitConvertCoefficient || 1);
  return data;
}
function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = "batchKey" + selectBatchInfo.value.index;
      setVal(className);
      selectBatchInfo.value.popoVisible = false;
      return;
    }
    let className = "batchKey" + selectBatchInfo.value.index;
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector(".el-input__inner");
    batchKeyDom.blur();
  });
}

//选择出库原出库仓库
function selectExportDepot() {
  selectExportDepotInfo.query.idNot = formInfo.data.depotId;
  selectExportDepotInfo.visible = true;
}
//选择入库原出库仓库
// function selectStoreDepot() {
//   selectStoreDepotInfo.query.idNot = formInfo.data.depotId
//   selectStoreDepotInfo.visible = true
// }
function selectConsumeDept() {
  deptInfo.visible = true;
}
function selectExportDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data.depotId = data.id;
    formInfo.data.depotName = data.name;
    uploadInfo.value.data.depotId = data.id;
    uploadInfo.value.data.depotName = data.name;
    // formInfo.data.consumeDeptName = data.consumeDeptName || ''
    // formInfo.data.consumeDeptId = data.consumeDeptId || ''
    selectProductInfo.value.query.queryMap.depotId.value = data.id;
    selectBatchInfo.value.query.queryMap.depotId.value = data.id;
    individualInfo.value.leftQuery.queryMap.depotId.value = data.id;
    tableInfo.data = [
      {
        emptyRowType: "1",
        productKeyword: "",
        batchKeyword: "",
        id: new Date().getTime() + (1 + Math.random()),
      },
    ];
    scanInfo.query.queryParams.depotId = data.id;
  } else {
    formInfo.data.depotId = "";
    formInfo.data.depotName = "";
    uploadInfo.value.data.depotId = "";
    uploadInfo.value.data.depotName = "";
    // formInfo.data.consumeDeptName = ''
    // formInfo.data.consumeDeptId = ''
    selectProductInfo.value.query.queryMap.depotId.value = "";
    selectBatchInfo.value.query.queryMap.depotId.value = "";
    individualInfo.value.leftQuery.queryMap.depotId.value = "";
    tableInfo.data = [
      {
        emptyRowType: "1",
        productKeyword: "",
        batchKeyword: "",
        id: new Date().getTime() + (1 + Math.random()),
      },
    ];
    scanInfo.query.queryParams.depotId = "";
  }
}
// function selectStoreDepotCallBack(data = undefined) {
//   if (data && data.id) {
//     formInfo.data.depotId = data.id
//     formInfo.data.depotName = data.name
//     // formInfo.data.consumeDeptName = data.consumeDeptName || ''
//     // formInfo.data.consumeDeptId = data.consumeDeptId || ''
//   } else {
//     formInfo.data.depotId = ''
//     formInfo.data.depotName = ''
//     // formInfo.data.consumeDeptName = ''
//     // formInfo.data.consumeDeptId = ''
//   }
// }
function largeMax(row) {
  return row.canInvalidQty;
  // if (row.qtyOperateMode === 2) {
  //   return parseInt(row.canInvalidCalcQty / row.unitConvertCoefficient)
  // } else {
  // return row.canInvalidQty
  // }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.canInvalidCalcQty / row.unitConvertCoefficient
  );
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.canInvalidCalcQty % row.unitConvertCoefficient);
  } else {
    return row.unitConvertCoefficient - 1;
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str);
  let largeUnitQty = parseInt(
    row.canInvalidCalcQty / row.unitConvertCoefficient
  );
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.canInvalidCalcQty % row.unitConvertCoefficient
      );
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty;
      }
    }
  }
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    );
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    );
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    );
    row.details[0].largeUnitQty = row.largeUnitQty;
    row.details[0].smallUnitQty = row.smallUnitQty;
    row.details[0].calcQty = row.calcQty;
    row.details[0].qty = row.qty;
    row.details[0].sumAmount = row.sumAmount;

    row.details[0].invalidCalcQty = row.calcQty;
    row.details[0].invalidQty = row.qty;
  }
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str);
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    );
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    );
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    );
    row.details[0].largeUnitQty = row.largeUnitQty;
    row.details[0].smallUnitQty = row.smallUnitQty;
    row.details[0].calcQty = row.calcQty;
    row.details[0].qty = row.qty;
    row.details[0].sumAmount = row.sumAmount;
  }
}
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.selections = [...data];
      break;
  }
}
function countData(data) {
  // if (data.canInvalidCalcQty > data.unitConvertCoefficient) {
  //   data.calcQty = data.unitConvertCoefficient
  //   data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
  //   data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
  //   data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
  //   data.sumAmount = proxy.$fn.accDiv(
  //     proxy.$fn.accMul(data.calcQty, data.price),
  //     data.unitConvertCoefficient
  //   )
  // } else {
  //   data.calcQty = data.canInvalidCalcQty
  //   data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
  //   data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
  //   data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
  //   data.sumAmount = proxy.$fn.accDiv(
  //     proxy.$fn.accMul(data.calcQty, data.price),
  //     data.unitConvertCoefficient
  //   )
  // }
  // data._key = data.storeBatchNumber + '-' + data.supplierId + '-' + data.price
  let str = "";
  tableInfo.sysGroup.forEach((item) => {
    if (
      !groupKeysFilter.value[
        formInfo.data.consumeRevokeDimensionType + ""
      ].includes(item)
    ) {
      if (item === "productionDate" || item === "validityDate") {
        str = str + (data[item] || "1900-01-01") + "";
      } else {
        str = str + data[item] + "";
      }
    }
  });
  if (formInfo.data.consumeRevokeDimensionType == 1) {
    data._key =
      data.orderNo +
      "-" +
      data.batchNumber +
      "-" +
      data.productionDate +
      "-" +
      data.validityDate +
      "-" +
      data.storeBatchNumber +
      "-" +
      data.supplierId +
      "-" +
      data.price +
      "-" +
      data.isConsignBusiness +
      "-" +
      data.isEstimationStockBusiness;
  }
  if (formInfo.data.consumeRevokeDimensionType == 2) {
    data._key =
      data.orderNo +
      "-" +
      data.storeBatchNumber +
      "-" +
      data.supplierId +
      "-" +
      data.price +
      "-" +
      data.isConsignBusiness +
      "-" +
      data.isEstimationStockBusiness;
  }
  if (formInfo.data.consumeRevokeDimensionType == 3) {
    data._key = data.orderNo;
  }
  return data;
}
function tableCellClassName({ column, row }) {
  if (row.isChoice && bgColor.value[formInfo.data.consumeRevokeDimensionType + ""].includes(column.property)) {
    return "success-row";
  }
  if (row.isLessData && ["preInvalidQty", "qty"].includes(column.property)) {
    return "warning-row";
  } else {
    return "";
  }
}
function addBucth(row, index) {
  batchNumberSearch(row, index);
}
function removeProduct() {
  proxy
    .$confirm("删除后将改变数据,是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      let groupKeys = tableInfo.selections.map((item) => item.groupKey);
      tableInfo.data = tableInfo.data.filter(
        (item) => !groupKeys.includes(item.groupKey)
      );
      if (!tableInfo.data.length) {
        tableInfo.data = [
          {
            emptyRowType: "1",
            productKeyword: "",
            batchKeyword: "",
            id: new Date().getTime() + (1 + Math.random()),
          },
        ];
      } else {
        let index = tableInfo.data.findIndex(
          (item) => item.emptyRowType === "1"
        );
        if (index === -1) {
          tableInfo.data.push({
            emptyRowType: "1",
            productKeyword: "",
            batchKeyword: "",
            id: new Date().getTime() + (1 + Math.random()),
          });
        }
      }
      const data = proxy.$fn.deepClone(tableInfo.data);
      tableInfo.data = [];
      proxy.$nextTick(() => {
        tableInfo.data = data;
      });
    });
}
// 用于存储groupKey对应批次数量
const groupKeyMap = ref({});
function setSuplierIdMap() {
  let _data = tableInfo.data.filter((element) => {
    return element.groupKey;
  });
  groupKeyMap.value = _.groupBy(_data, "groupKey");
}
function removeBatch(row, index) {
  let keys = keysTable.value[formInfo.data.consumeRevokeDimensionType + ""];
  if (row.codeType === 1 || row.codeType === 4) {
    if (
      groupKeyMap.value[row.groupKey] &&
      groupKeyMap.value[row.groupKey]?.length > 1
    ) {
      tableInfo.data = tableInfo.data.filter((item) => ![row].includes(item));
    } else {
      tableInfo.data[index] = {
        commonName: !keys.includes("commonName") ? row.commonName : "",
        productCode: !keys.includes("productCode") ? row.productCode : "",
        groupKey: !keys.includes("groupKey") ? row.groupKey : "",
        standard: !keys.includes("standard") ? row.standard : "",
        brandName: !keys.includes("brandName") ? row.brandName : "",
        brandId: !keys.includes("brandId") ? row.brandId : "",
        unitName: !keys.includes("unitName") ? row.unitName : "",
        unitId: !keys.includes("unitId") ? row.unitId : "",
        codeTypeValue: !keys.includes("codeTypeValue") ? row.codeTypeValue : "",
        codeType: !keys.includes("codeType") ? row.codeType : "",
        batchNumber: !keys.includes("batchNumber") ? row.batchNumber : "",
        productionDate: !keys.includes("productionDate")
          ? row.productionDate
          : "",
        validityDate: !keys.includes("validityDate") ? row.validityDate : "",
        depotStockId: !keys.includes("depotStockId") ? row.depotStockId : "",
        productId: !keys.includes("productId") ? row.productId : "",
        storeBatchNumber: !keys.includes("storeBatchNumber")
          ? row.storeBatchNumber
          : "",
        supplierName: !keys.includes("supplierName") ? row.supplierName : "",
        supplierId: !keys.includes("supplierId") ? row.supplierId : "",
        price: !keys.includes("price") ? row.price : "",
        orgId: !keys.includes("orgId") ? row.orgId : "",
        productId: !keys.includes("productId") ? row.productId : "",
        isConsignBusiness:
          !keys.includes("isConsignBusiness") &&
          formInfo.data.consumeRevokeDimensionType == 3
            ? row.isConsignBusiness
            : "",
        isEstimationStockBusiness:
          !keys.includes("isEstimationStockBusiness") &&
          formInfo.data.consumeRevokeDimensionType == 3
            ? row.isEstimationStockBusiness
            : "",
        emptyRowType: "2",
      };
    }
  } else if (row.codeType === 2 || row.codeType === 3) {
    tableInfo.data[index] = {
      commonName: !keys.includes("commonName") ? row.commonName : "",
      productCode: !keys.includes("productCode") ? row.productCode : "",
      groupKey: !keys.includes("groupKey") ? row.groupKey : "",
      standard: !keys.includes("standard") ? row.standard : "",
      brandName: !keys.includes("brandName") ? row.brandName : "",
      brandId: !keys.includes("brandId") ? row.brandId : "",
      unitName: !keys.includes("unitName") ? row.unitName : "",
      unitId: !keys.includes("unitId") ? row.unitId : "",
      codeTypeValue: !keys.includes("codeTypeValue") ? row.codeTypeValue : "",
      codeType: !keys.includes("codeType") ? row.codeType : "",
      batchNumber: !keys.includes("batchNumber") ? row.batchNumber : "",
      productionDate: !keys.includes("productionDate")
        ? row.productionDate
        : "",
      validityDate: !keys.includes("validityDate") ? row.validityDate : "",
      depotStockId: !keys.includes("depotStockId") ? row.depotStockId : "",
      productId: !keys.includes("productId") ? row.productId : "",
      storeBatchNumber: !keys.includes("storeBatchNumber")
        ? row.storeBatchNumber
        : "",
      supplierName: !keys.includes("supplierName") ? row.supplierName : "",
      supplierId: !keys.includes("supplierId") ? row.supplierId : "",
      price: !keys.includes("price") ? row.price : "",
      orgId: !keys.includes("orgId") ? row.orgId : "",
      productId: !keys.includes("productId") ? row.productId : "",
      isConsignBusiness:
        !keys.includes("isConsignBusiness") &&
        formInfo.data.consumeRevokeDimensionType == 3
          ? row.isConsignBusiness
          : "",
      isEstimationStockBusiness:
        !keys.includes("isEstimationStockBusiness") &&
        formInfo.data.consumeRevokeDimensionType == 3
          ? row.isEstimationStockBusiness
          : "",
      emptyRowType: "2",
    };
    let list = tableInfo.data.filter((item) => item.groupKey === row.groupKey);
    tableInfo.data = tableInfo.data.filter((item, i) => {
      if (!list.includes(item) || index === i) {
        return item;
      }
    });
  }
}
function individualDetails(row, index) {
  console.log(row)
  let list = tableInfo.data.filter((item) => item.groupKey === row.groupKey);
  console.log(list)
  // let depotStockIds = [];
  let groupConcatId = [];
  let details = [];
  let isRequest = false;
  if (list.length) {
    list.forEach((item) => {
      if (item.details && item.details.length) {
        details = details.concat(item.details);
      }
      if (
        !item.details &&
        item.groupConcatIds &&
        item.groupConcatDepotStockIds
      ) {
        isRequest = true;
      }
      if (item.groupConcatIds) {
        groupConcatId.push(item.groupConcatIds);
      }
      // if (item.groupConcatDepotStockIds) {
      //   depotStockIds.push(item.groupConcatDepotStockIds);
      // }
    });
  }
  individualInfo.value.row = row;
  individualInfo.value.details = details;
  individualInfo.value.index = index;
  
  individualInfo.value.leftQuery.queryMap.orgId.value = row.orgId;
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId;
  if (formInfo.data.consumeRevokeDimensionType == 3) {
    individualInfo.value.leftQuery.queryMap.isConsignBusiness.value =
      row.isConsignBusiness;
    individualInfo.value.rightQuery.queryMap.isConsignBusiness.value =
      row.isConsignBusiness;
    individualInfo.value.leftQuery.queryMap.isEstimationStockBusiness.value =
      row.isEstimationStockBusiness;
    individualInfo.value.rightQuery.queryMap.isEstimationStockBusiness.value =
      row.isEstimationStockBusiness;
    individualInfo.value.leftQuery.queryMap.storeBatchNumber = {
      queryType: "EQUALS",
      queryCategory: "AND",
      value: row.storeBatchNumber,
    };
    individualInfo.value.leftQuery.queryMap.supplierId = {
      queryType: "EQUALS",
      queryCategory: "AND",
      value: row.supplierId,
    };
    individualInfo.value.leftQuery.queryMap.price = {
      queryType: "EQUALS",
      queryCategory: "AND",
      value: row.price,
    };
  } else {
    delete individualInfo.value.leftQuery.queryMap.storeBatchNumber;
    delete individualInfo.value.leftQuery.queryMap.supplierId;
    delete individualInfo.value.leftQuery.queryMap.price;

    individualInfo.value.leftQuery.queryMap.isConsignBusiness.value = ''
    individualInfo.value.rightQuery.queryMap.isConsignBusiness.value = ''
    individualInfo.value.leftQuery.queryMap.isEstimationStockBusiness.value = ''
    individualInfo.value.rightQuery.queryMap.isEstimationStockBusiness.value = ''
    
  }

  if (formInfo.data.consumeRevokeDimensionType != 1) {
    if (row.batchNumber) {
      individualInfo.value.leftQuery.queryMap.batchNumber = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.batchNumber,
      };
    } else {
      individualInfo.value.leftQuery.queryMap.batchNumber = {
        queryType: "NULL",
        queryCategory: "AND",
        value: "",
      };
    }
    if (row.validityDate) {
      individualInfo.value.leftQuery.queryMap.validityDate = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.validityDate,
      };
    } else {
      individualInfo.value.leftQuery.queryMap.validityDate = {
        queryType: "NULL",
        ignoreEmptyValue: false,
        queryCategory: "AND",
        value: null,
      };
    }
    if (row.productionDate) {
      individualInfo.value.leftQuery.queryMap.productionDate = {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: row.productionDate,
      };
    } else {
      individualInfo.value.leftQuery.queryMap.productionDate = {
        queryType: "NULL",
        ignoreEmptyValue: false,
        queryCategory: "AND",
        value: null,
      };
    }
  } else {
    delete individualInfo.value.leftQuery.queryMap.batchNumber;
    delete individualInfo.value.leftQuery.queryMap.validityDate;
    delete individualInfo.value.leftQuery.queryMap.productionDate;
  }
  // individualInfo.value.leftQuery.queryMap.batchNumber.value =
  //   row.batchNumber || ''
  // individualInfo.value.leftQuery.queryMap.validityDate.value =
  //   row.validityDate || ''
  // individualInfo.value.leftQuery.queryMap.productionDate.value =
  //   row.productionDate || ''
  individualInfo.value.leftQuery.queryMap.id.value = groupConcatId.length
    ? groupConcatId.toString()
    : "";
  individualInfo.value.rightQuery.queryMap.id.value = props.orderId
    ? details.length
      ? ""
      : groupConcatId.toString()
    : "";
  individualInfo.value.isRequest = isRequest;
  individualInfo.value.rightQuery.queryMap.orderId.value = props.orderId;
  console.log(row);
  individualInfo.value.visible = true;
  individualInfo.value.codeType = row.codeType;
}
function individualCallback(data) {
  let index = individualInfo.value.index;
  let row = individualInfo.value.row;
  if (data.length) {
    let groupData = _.groupBy(data, "_key");
    let groupKeys = Object.keys(groupData);
    let groupKeysIn = [];
    tableInfo.data = tableInfo.data.filter((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          return groupKeys.includes(item._key);
        } else {
          return item;
        }
      } else {
        return item;
      }
    });
    tableInfo.data.forEach((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          if (groupKeys.includes(item._key)) {
            groupKeysIn.push(item._key);
            item.details = groupData[item._key];
            item = countQty(item);
          }
        }
      }
    });
    let list = [];
    if (groupKeysIn.length) {
      groupKeys.forEach((item) => {
        if (!groupKeysIn.includes(item)) {
          let groupDataItem = groupData[item];
          let obj = proxy.$fn.deepClone(groupDataItem[0]);
          obj.details = proxy.$fn.deepClone(groupDataItem);
          obj.groupKey = row.groupKey;
          obj = countQty(obj);
          obj.canInvalidQty = obj.mergeStockAvailableQty || 0;
          obj.canInvalidCalcQty = obj.mergeStockAvailableCalcQty || 0;
          list.push(obj);
        }
      });
    } else {
      let values = Object.values(groupData);
      values.forEach((item) => {
        let obj = proxy.$fn.deepClone(item[0]);
        obj.details = proxy.$fn.deepClone(item);
        obj.groupKey = row.groupKey;
        obj = countQty(obj);
        obj.canInvalidQty = obj.mergeStockAvailableQty || 0;
        obj.canInvalidCalcQty = obj.mergeStockAvailableCalcQty || 0;
        list.push(obj);
      });
    }
    if (list.length) {
      let newData = tableInfo.data[index];
      let leftList = [];
      if (newData._key) {
        leftList = tableInfo.data.slice(0, index + 1);
      } else {
        leftList = tableInfo.data.slice(0, index);
      }
      let rightList = tableInfo.data.slice(index + 1);
      tableInfo.data = leftList.concat(list).concat(rightList);
    }
  } else {
    tableInfo.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupKey: row.groupKey,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      batchNumber: row.batchNumber,
      productionDate: row.productionDate,
      validityDate: row.validityDate,
      depotStockId: row.depotStockId,
      productId: row.productId,
      orgId: row.orgId,
      emptyRowType: "2",
    };
    tableInfo.data = tableInfo.data.filter((item) => {
      if (row.groupKey === item.groupKey) {
        return item.emptyRowType === "2";
      } else {
        return item;
      }
    });
  }
  let emptyIndex = tableInfo.data.findIndex(
    (item) => item.emptyRowType === "1"
  );
  if (emptyIndex === -1) {
    tableInfo.data.push({
      emptyRowType: "1",
      productKeyword: "",
      batchKeyword: "",
      id: new Date().getTime() + (1 + Math.random()),
    });
  }
}
async function onCallBackScanData(data, callback) {
  
  let { mergeDetail, detail } = data;
  let str = "";
  mergeDetail = mergeDetail[0];

  tableInfo.sysGroup.forEach((item) => {
    if (
      !groupKeysFilter.value[
        formInfo.data.consumeRevokeDimensionType + ""
      ].includes(item)
    ) {
      if (item === "productionDate" || item === "validityDate") {
        str = str + (mergeDetail[item] || "1900-01-01") + "";
      } else {
        str = str + mergeDetail[item] + "";
      }
    }
  });
  // 2023021028 2023021029 2023021030 2023021031
  // R37|CP000976|GYS416|OS0000000217|||| 
  // R37|CP000976|GYS417|OS0000000233|222222|20240216|20230131|
  mergeDetail.groupKey = str;
  if (formInfo.data.consumeRevokeDimensionType == 1) {
    detail._key =
      detail.orderNo +
      "-" +
      detail.batchNumber +
      "-" +
      detail.productionDate +
      "-" +
      detail.validityDate +
      "-" +
      detail.storeBatchNumber +
      "-" +
      detail.supplierId +
      "-" +
      detail.price +
      "-" +
      detail.isConsignBusiness +
      "-" +
      detail.isEstimationStockBusiness;
  }
  if (formInfo.data.consumeRevokeDimensionType == 2) {
    detail._key =
      detail.orderNo +
      "-" +
      detail.storeBatchNumber +
      "-" +
      detail.supplierId +
      "-" +
      detail.price +
      "-" +
      detail.isConsignBusiness +
      "-" +
      detail.isEstimationStockBusiness;
  }
  if (formInfo.data.consumeRevokeDimensionType == 3) {
    detail._key = detail.orderNo;
  }
 
  let unitConvertCoefficient = detail.unitConvertCoefficient || 1;
  if (tableInfo.data && tableInfo.data.length) {
    tableInfo.data.forEach((item) => {
      item.isChoice = false;
    });
    let list = tableInfo.data.filter(
      (item) => item.groupKey === mergeDetail.groupKey
    );
    if (list.length) {
      let index = tableInfo.data.findIndex(
        (item) =>
          item.groupKey === mergeDetail.groupKey &&
          item._key &&
          item._key === detail._key
      );
      if (index > -1) {
        if (
          tableInfo.data[index].calcQty ===
          tableInfo.data[index].canInvalidCalcQty
        ) {
          callback(true);
          return;
        }
        if (
          props.orderId &&
          !tableInfo.data[index].details &&
          tableInfo.data[index].groupConcatDepotStockIds &&
          tableInfo.data[index].groupConcatIds
        ) {
          await getIndividualRight(tableInfo.data[index].groupConcatIds).then(
            (res) => {
              tableInfo.data[index].details = res;
            }
          );
        }
        let haveIndex = tableInfo.data[index].details.findIndex(
          (item) => item.id == detail.id
        );
        if (detail.codeType === 2 || detail.codeType === 3) {
          if (haveIndex > -1) {
            callback(true);
          } else {
            tableInfo.data[index].details.push(detail);
            tableInfo.data[index] = countQty(tableInfo.data[index]);
            tableInfo.data[index].isChoice = true;
          }
        } else if (detail.codeType === 4) {
          let num = proxy.$fn.Subtr(
            tableInfo.data[index].canInvalidCalcQty,
            tableInfo.data[index].calcQty
          );
          if (haveIndex > -1) {
            if (num > unitConvertCoefficient) {
              tableInfo.data[index].details[haveIndex].calcQty =
                proxy.$fn.accAdd(
                  tableInfo.data[index].details[haveIndex].calcQty || 0,
                  1
                );
            } else {
              tableInfo.data[index].details[haveIndex].calcQty =
                tableInfo.data[index].details[haveIndex].canInvalidCalcQty;
            }
            console.log(tableInfo.data[index].details[haveIndex].canInvalidCalcQty)
            tableInfo.data[index].details[haveIndex].largeUnitQty = parseInt(
              tableInfo.data[index].details[haveIndex].calcQty /
                unitConvertCoefficient
            );
            tableInfo.data[index].details[haveIndex].smallUnitQty = parseInt(
              tableInfo.data[index].details[haveIndex].calcQty %
                unitConvertCoefficient
            );
            tableInfo.data[index].details[haveIndex].qty = proxy.$fn.accDiv(
              tableInfo.data[index].details[haveIndex].calcQty,
              unitConvertCoefficient
            );
            tableInfo.data[index].details[haveIndex].sumAmount =
              proxy.$fn.accDiv(
                proxy.$fn.accMul(
                  tableInfo.data[index].details[haveIndex].calcQty,
                  tableInfo.data[index].details[haveIndex].price
                ),
                unitConvertCoefficient
              );
            tableInfo.data[index] = countQty(tableInfo.data[index]);
            tableInfo.data[index].isChoice = true;
          } else {
            tableInfo.data[index].details.push(detail);
            tableInfo.data[index] = countQty(tableInfo.data[index]);
            tableInfo.data[index].isChoice = true;
          }
        }
      } else {
        let newIndex = tableInfo.data.findIndex(
          (item) =>
            item.groupKey === mergeDetail.groupKey &&
            item.emptyRowType &&
            item.emptyRowType === "2"
        );
        if (newIndex > -1) {
          mergeDetail.details = [detail];
          mergeDetail._key = detail._key;
          mergeDetail = countQty(mergeDetail);
          tableInfo.data[newIndex] = mergeDetail;
        } else {
          let spliceIndex = tableInfo.data.findIndex(
            (item) => item.id == list[list.length - 1].id
          );
          mergeDetail.details = [detail];
          mergeDetail._key = detail._key;
          mergeDetail = countQty(mergeDetail);
          if(tableInfo.data[spliceIndex]['isExport']) {
            mergeDetail['isExport'] = true
          }
          tableInfo.data.splice(spliceIndex, 0, mergeDetail);
        }
      }
    } else {
      let list = tableInfo.data.filter((item) => item.depotStockId);
      mergeDetail.details = [detail];
      mergeDetail._key = detail._key;
      if (list.length) {
        let index = tableInfo.data.findIndex(
          (item) => item.id == list[list.length - 1].id
        );
        tableInfo.data.splice(index + 1, 0, mergeDetail);
      } else {
        tableInfo.data.unshift(mergeDetail);
      }
      mergeDetail = countQty(mergeDetail);
      callback(false);
    }
  }
  
  console.log(tableInfo.data)
  setSuplierIdMap();
}
function getIndividualRight(ids) {
  return new Promise((resolve, reject) => {
    let param = {
      customizeUserVO: individualInfo.value.rightVo,
      queryMap: {
        id: {
          queryType: "IN",
          queryCategory: "AND",
          value: ids,
        },
      },
      queryParams: {},
    };
    getConsumeOrderDetailCustomizeListAll(param).then((resp) => {
      if (resp && resp.success) {
        let data = resp.data;
        data.forEach((item) => {
          item.isChoice = false;
        });
        resolve(data);
      } else {
        reject();
      }
    });
  });
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetailsList = tableInfo.data.filter(
      (row) => row.productId && row.depotStockId
    );
    if (!newDetailsList.length) {
      proxy.$message({
        message: "请添加有效的产品",
        type: "warning",
        duration: 3500,
        showClose: true,
      });
      return;
    }
    let emptyDetails = newDetailsList
      .filter((item) => item.emptyRowType === "2")
      .map((item) => item.commonName);
    if (emptyDetails.length) {
      proxy.$message({
        message: "请添产品【" + emptyDetails + "】的批次信息",
        type: "warning",
        duration: 3500,
        showClose: true,
      });
      return;
    }
    newDetailsList.map((row) => {
      if (row.codeType === 1 || row.codeType === 4) {
        row.calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(
            row.largeUnitQty || 0,
            row.unitConvertCoefficient || 1
          ),
          row.smallUnitQty || 0
        );
        row.qty = proxy.$fn.accDiv(
          row.calcQty || 0,
          row.unitConvertCoefficient || 1
        );
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
          row.unitConvertCoefficient || 1
        );
        row.details[0].largeUnitQty = row.largeUnitQty;
        row.details[0].smallUnitQty = row.smallUnitQty;
        row.details[0].calcQty = row.calcQty;
        row.details[0].qty = row.qty;
        row.details[0].sumAmount = row.sumAmount;

        row.details[0].invalidCalcQty = row.calcQty;
        row.details[0].invalidQty = row.qty;
      } if (row.codeType === 2 || row.codeType === 3) {
        row.details.forEach((el) => {
          let calcQty = 0
          calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0);
          el.invalidCalcQty = el.calcQty;
          el.invalidQty = proxy.$fn.accDiv(calcQty, el.unitConvertCoefficient || 1);

          el.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(calcQty, el.price || 0),
            el.unitConvertCoefficient || 1
          );
        })
      }
    });
    let newDetails = newDetailsList.filter((item) => item.calcQty > 0);
    // newDetails = newDetails.filter(i => {
    //   return i.emptyRowType != 1
    // })
    let findisLessData = newDetailsList.find((item) => item.isLessData);
    if (findisLessData) {
      proxy
        .$confirm(
          "无法完全匹配预撤回数量，是否确认提交已匹配的数据？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            dangerouslyUseHTMLString: true,
          }
        )
        .then(() => {
          reSave(newDetails);
        })
        .catch(() => {
          return;
        });
    } else {
      reSave(newDetails);
    }
  });
}
function reSave(newDetails) {
  const data = formInfo.data;
  data.mergeDetails = proxy.$fn.filterBlacklist(newDetails);
  batchRevokeSubmit(data).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false;
      emit("returnModify", false);
      if (resp && resp.success) {
        tableInfo.data = [];
        initTableRow();
        selectDepotStorageInfo.excludeQueryList = [];
        tableInfo.map = new Map();
      }
    }
  });
}
function validateExpire(list = []) {
  let currentDate = moment().format("YYYY-MM-DD");
  let msg = "";
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`;
    }
  });
  return msg;
}
function getMain() {
  detailConsumeOrder(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data;
      scanInfo.query.queryParams.depotId = resp.data.depotId;
      scanInfo.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness;
      selectProductInfo.value.query.queryMap.depotId.value = resp.data.depotId;
      selectProductInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness;
      selectBatchInfo.value.query.queryMap.depotId.value = resp.data.depotId;
      selectBatchInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness;
      individualInfo.value.leftQuery.queryMap.depotId.value = resp.data.depotId;
      individualInfo.value.leftQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness;
      individualInfo.value.rightQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness;
    }
  });
  filterInfo.query.queryMap.orderId.value = props.orderId;
  getList();
  setBusinessDate();
}
function getList() {
  //修改请求明细信息
  getConsumeOrderDetailCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data;
      data.forEach((row) => {
        let str = "";
        tableInfo.sysGroup.forEach((item) => {
          if (
            !groupKeysFilter.value[
              formInfo.data.consumeRevokeDimensionType + ""
            ].includes(item)
          ) {
            if (item === "productionDate" || item === "validityDate") {
              str = str + (row[item] || "1900-01-01") + "";
            } else {
              str = str + row[item] + "";
            }
          }
        });
        row.groupKey = str;
        if (formInfo.data.consumeRevokeDimensionType == 1) {
          row._key =
            row.orderNo +
            "-" +
            row.batchNumber +
            "-" +
            row.productionDate +
            "-" +
            row.validityDate +
            "-" +
            row.storeBatchNumber +
            "-" +
            row.supplierId +
            "-" +
            row.price +
            "-" +
            row.isConsignBusiness +
            "-" +
            row.isEstimationStockBusiness;
        }
        if (formInfo.data.consumeRevokeDimensionType == 2) {
          row._key =
            row.orderNo +
            "-" +
            row.storeBatchNumber +
            "-" +
            row.supplierId +
            "-" +
            row.price +
            "-" +
            row.isConsignBusiness +
            "-" +
            row.isEstimationStockBusiness;
        }
        if (formInfo.data.consumeRevokeDimensionType == 3) {
          row._key = row.orderNo;
        }
        if (row.codeType === 1 || row.codeType === 4) {
          let detail = proxy.$fn.deepClone(row);
          row.details = [detail];
        }
      });
      tableInfo.data = data;
      initTableRow();
    }
  });
}
function initTableRow() {
  tableInfo.data.push({
    emptyRowType: "1",
    productKeyword: "",
    batchKeyword: "",
    id: new Date().getTime() + (1 + Math.random()),
  });
}
function getCustomize() {
  let param = {
    // 新增
    tableKey:
      getCustomizeKey.value[formInfo.data.consumeRevokeDimensionType / 1],
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.query.customizeUserVO = data;
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      );
      tableInfo.fieldList = tableInfo.fieldList.filter((item) => {
        return item.showLevel > 0;
      });
      let arr = [];
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel });
        }
      }
      arr = proxy.$fn.getSort(arr, "sysGroupLevel");
      arr = arr.map((element) => {
        return element.key;
      });
      selectBatchInfo.value.query.queryParams.groupField = arr.length
        ? arr.toString()
        : "";
      individualInfo.value.leftQuery.queryParams.groupField = arr.length
        ? arr.toString()
        : "";
        scanInfo.query.queryParams.groupField = arr.length
        ? arr.toString()
        : "";
      uploadInfo.value.data.groupField = arr.length
        ? arr.toString()
        : "";
      // tableInfo.sysGroup = arr;
      if (props.orderId) {
        getMain();
      } else {
        setBusinessDate();
      }
    }
  });
}
function getScanCustomize() {
  let param = {
    // 扫码
    tableKey: 'batchConsumeRevokeScan-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO'
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      scanInfo.query.customizeUserVO = data;
    }
  });
}
function getProductCustomize() {
  let param = {
    // 通用名称搜索
    tableKey:
      getProductCustomizeKey.value[
        formInfo.data.consumeRevokeDimensionType / 1
      ],
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      let arr = [];
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({
            columnName: data.detail[key].columnName,
            asTbName: data.detail[key].asTbName,
            key: key,
          });
        }
      }
      tableInfo.productSysGroup = arr;

      let arr1 = [];
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr1.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel });
        }
      }
      arr1 = proxy.$fn.getSort(arr1, "sysGroupLevel");
      arr1 = arr1.map((element) => {
        return element.key;
      });
      tableInfo.sysGroup = arr1;
    }
  });
}
function getIndividualRightCustomize() {
  let param = {
    // 个体详情右边搜索
    tableKey: rightTableKey.value,
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      individualInfo.value.rightVo = data;
    }
  });
}
let obj = {
  productCode: {
    label: "产品编码",
    value: "productCode",
    type: "slot",
    minWidth: "100px",
  },
  orderNo: {
    label: "消耗单号",
    value: "orderNo",
    type: "slot",
    align: "left",
    minWidth: "100px",
  },
  storeBatchNumber: {
    label: "入库批次号",
    value: "storeBatchNumber",
    type: "slot",
  },
  price: {
    label: "单价",
    value: "price",
    type: "slot",
  },
  preInvalidQty: {
    label: "预撤回数量",
    value: "preInvalidQty",
    type: "slot",
  },
  qty: {
    label: "实际撤回数量",
    value: "qty",
    type: "slot",
  },
};

tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
});
getCustomize();
getProductCustomize();
getScanCustomize();
getIndividualRightCustomize();
</script>
<style lang="scss" scoped>
.el-input-search {
  width: 100%;
  height: 100%;
}
.isShow {
  :deep(.el-scrollbar__wrap) {
    overflow: inherit;
  }
}
.el-popper {
  overflow-y: hidden;
}
</style>
<style>
.el-popper {
  max-height: max-content !important;
}
.popover-wrapper {
  height: 385.59px;
}
</style>
